package org.next.tesigiulia.utils;


import com.google.common.eventbus.Subscribe;
import org.next.tesigiulia.models.Area;
import twitter4j.Twitter;

import java.util.ArrayList;
import java.util.HashMap;

public class TwitterAreaHandler {

    private Twitter twitter;
    private TwitterAreaBuilder twitterAreaBuilder;
    private HashMap<String, TwitterArea> areeAvviate = new HashMap<String, TwitterArea>();

    public TwitterAreaHandler(TwitterAreaBuilder twitterAreaBuilder, Twitter twitter) {

        this.twitter = twitter;
        this.twitterAreaBuilder = twitterAreaBuilder;

        MyEventBus.getInstance().getEventBus().register(this);

    }


    @Subscribe
    public void handleListaAree(ArrayList<Area> list) {

        for (TwitterArea twitterArea : areeAvviate.values()) {
            twitterArea.stop();
        }
        areeAvviate.clear();

        for (int i = 0; i < list.size(); i++) {

            String areanome = list.get(i).getAreaName();
            double lat = list.get(i).getLatitudine();
            double lon = list.get(i).getLongitudine();
            int rag = list.get(i).getRaggio();

            TwitterArea ta = twitterAreaBuilder.createTwitterArea(twitter, lat, lon, rag);
            ta.start();
            areeAvviate.put(areanome, ta);

        }

    }


    @Subscribe
    public void handleArea(Area area) {
        String nome = area.getAreaName();
        Double lat = area.getLatitudine();
        Double lon = area.getLongitudine();

        if (nome == null || lat == null || lon == null) {
            return;
        }

        int rag = area.getRaggio();

        TwitterArea ta = areeAvviate.get(nome);
        if (ta != null) {
            ta.stop();
            areeAvviate.remove(ta);
        }

        ta = twitterAreaBuilder.createTwitterArea(twitter, lat, lon, rag);
        ta.start();
        areeAvviate.put(nome, ta);

    }

}
